package com.rcloud.server.sealtalk.controller;


import com.github.binarywang.java.emoji.EmojiConverter;
import com.github.pagehelper.PageInfo;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.controller.param.UserWechatMomentsParam;
import com.rcloud.server.sealtalk.domain.UserWechatMoments;
import com.rcloud.server.sealtalk.domain.Users;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.model.response.APIResult;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.service.FriendshipsService;
import com.rcloud.server.sealtalk.service.UserWechatMomentsService;
import com.rcloud.server.sealtalk.service.UsersService;
import com.rcloud.server.sealtalk.util.N3d;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.*;


/**
 * 用户朋友圈相关接口
 */
@Api(tags = "用户朋友圈相关接口")
@Slf4j
@RestController
@RequestMapping("/user/wechat/moments")
@AllArgsConstructor
public class UserWechatMomentsController extends BaseController {

    private UserWechatMomentsService wechatMomentsService;

    private UsersService usersService;

    private FriendshipsService friendshipsService;


    @ApiOperation("朋友圈信息发布的接口")
    @PostMapping("/submitMoments")
    public APIResult<Object> submitMoments(@RequestBody UserWechatMomentsParam param) throws ServiceException {
        if (StringUtils.isEmpty(param.getContent()) && StringUtils.isEmpty(param.getImageUrl())) {
            throw new ServiceException(ErrorCode.WECHAT_PARAMS_NOT_EMPTY);
        }
        Integer userId = getCurrentUserId();
        UserWechatMoments wechatMoments = UserWechatMoments.builder().build();
        // 进行emoji表情的转换
        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        wechatMoments.setContent(emojiConverter.toAlias(param.getContent()));
        wechatMoments.setCreateTime(new Date());
        //原始图片
        if (param.getImageUrl() != null && !"".equals(param.getImageUrl())) {
            wechatMoments.setImageUrl(param.getImageUrl());
        }
        //缩略图片
        if (param.getThumbnail() != null && !"".equals(param.getThumbnail())) {
            wechatMoments.setThumbnail(param.getImageUrl());
        }
        wechatMoments.setUserId(userId.toString());
        wechatMomentsService.saveSelective(wechatMoments);
        return APIResultWrap.ok("", "发布成功！");
    }

    /**
     * 查看最近的朋友圈信息
     */
    @GetMapping(value = "/queryWechatMomentImages/{id}")
    @ApiOperation(value = "查看最近的朋友圈信息", notes = "查看最近的朋友圈信息")
    public APIResult<Object> queryWechatMomentImages(@PathVariable String id) throws ServiceException {
        //获取当前登录用户的朋友圈信息
        Integer userId = N3d.decode(id);
        //查询用户的朋友圈信息
        Example example = new Example(UserWechatMoments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andIsNotNull("imageUrl");
        //注意：排序使用的是列名
        example.setOrderByClause("create_time DESC");
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", 1);
        map.put("pageSize", 4);
        map.put("example", example);
        List<UserWechatMoments>  userWechatMomentsList = wechatMomentsService.selectPageInfo(map).getList();
        List<String> userImageWechatMomentsList = new ArrayList<>();
        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        //提取用户的图片数据
        for (UserWechatMoments moments :userWechatMomentsList) {
            moments.setContent(emojiConverter.toUnicode(moments.getContent()));
            userImageWechatMomentsList.add(moments.getImageUrl());
        }
        return APIResultWrap.ok(userImageWechatMomentsList);
    }

    /**
     * 查看朋友圈信息
     */
    @GetMapping(value = "/queryWechatMomentsArray")
    @ApiOperation(value = "查看朋友圈信息", notes = "查看朋友圈信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示数量", required = true, dataType = "int", paramType = "query"),
    })
    public APIResult<Object> queryWechatMomentsArray(@RequestParam Integer pageNo,
                                                     @RequestParam Integer pageSize) throws ServiceException {
        Map<String,Object> resultMap = new HashMap<>();
        //获取当前登录用户的朋友圈信息
        Integer userId = getCurrentUserId();
        //当前登录用户的头像和背景图片
        Users loginUser = usersService.getByPrimaryKey(userId);
        Example example = new Example(UserWechatMoments.class);
        //获取我的好友用户信息
        List<Integer> friendShipUserIdList = friendshipsService.getFriendShipUserIdList(userId);
        //添加上自己的信息
        friendShipUserIdList.add(userId);
        example.createCriteria().andIn("userId", friendShipUserIdList);
        //注意：排序使用的是列名
        example.setOrderByClause("create_time DESC");
        //分页
        //条件查询使用的是属性名
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("example", example);
        //遍历放置用户信息
        PageInfo<UserWechatMoments> userWechatMomentsPageInfo = wechatMomentsService.selectPageInfo(map);
        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        for (UserWechatMoments moments : userWechatMomentsPageInfo.getList()) {
            moments.setContent(emojiConverter.toUnicode(moments.getContent()));
            Users users = usersService.getByPrimaryKey(Integer.parseInt(moments.getUserId()));
            moments.setUserId(N3d.encode(Long.parseLong(moments.getUserId())));
            moments.setUserNickname(users.getNickname());
            moments.setUserAvatar(users.getPortraitUri());
        }
        //设置返回数据
        resultMap.put("nickname",loginUser.getNickname());
        resultMap.put("background",loginUser.getBackground());
        resultMap.put("portraitUri",loginUser.getPortraitUri());
        resultMap.put("userWechatMomentsPageInfo",userWechatMomentsPageInfo);
        //todo 返回背景图片和头像
        return APIResultWrap.ok(resultMap);
    }

    /**
     * 查看我的朋友圈信息
     */
    @GetMapping(value = "/queryOtherWechatMoments")
    @ApiOperation(value = "查看他(她)人朋友圈信息", notes = "查看他(她)人朋友圈信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示数量", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "String", paramType = "query")
    })
    public APIResult<Object> queryMyWechatMoments(@RequestParam Integer pageNo,
                                                  @RequestParam Integer pageSize,
                                                  @RequestParam String userId) throws ServiceException {
        Map<String,Object> resultMap = new HashMap<>();

        //查询用户的头像和背景图片
        Users queryUser = usersService.getByPrimaryKey(N3d.decode(userId));

        Example example = new Example(UserWechatMoments.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", N3d.decode(userId));
        //注意：排序使用的是列名
        example.setOrderByClause("create_time DESC");
        //分页
        //条件查询使用的是属性名
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", pageNo);
        map.put("pageSize", pageSize);
        map.put("example", example);
        PageInfo<UserWechatMoments> userWechatMomentsPageInfo = wechatMomentsService.selectPageInfo(map);
        EmojiConverter emojiConverter = EmojiConverter.getInstance();
        //遍历放置用户信息
        for (UserWechatMoments moments : userWechatMomentsPageInfo.getList()) {
            moments.setContent(emojiConverter.toUnicode(moments.getContent()));
            Users users = usersService.getByPrimaryKey(Integer.parseInt(moments.getUserId()));
            moments.setUserId(N3d.encode(Long.parseLong(moments.getUserId())));
            moments.setUserNickname(users.getNickname());
            moments.setUserAvatar(users.getPortraitUri());
        }
        // 设置用户的返回数据
        resultMap.put("nickname",queryUser.getNickname());
        resultMap.put("background",queryUser.getBackground());
        resultMap.put("portraitUri",queryUser.getPortraitUri());
        resultMap.put("userWechatMomentsPageInfo",userWechatMomentsPageInfo);
        //todo 返回背景图片和头像
        return APIResultWrap.ok(resultMap);
    }

    /**
     * 查看我的朋友圈信息
     */
    @GetMapping(value = "/removeMyWechatMoments")
    @ApiOperation(value = "删除我的朋友圈信息", notes = "查看我的朋友圈信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "momentsId", value = "朋友圈信息ID", required = true, dataType = "int"),
    })
    public APIResult<Object> removeMyWechatMoments(@RequestParam Integer momentsId) throws ServiceException {
        Integer userId = getCurrentUserId();
        //判断信息是否存在
        UserWechatMoments byPrimaryKey = wechatMomentsService.getByPrimaryKey(momentsId);
        if (byPrimaryKey != null) {
            //判断是否是本人的朋友圈信息
            if (!byPrimaryKey.getUserId().equals(userId.toString())) {
                throw new ServiceException(ErrorCode.CAN_NOT_REMOVE_OTHER_MOMENTS_INFO);
            }
        }else {
            throw new ServiceException(ErrorCode.NOT_QUERY_MOMENTS_INFO);
        }
        wechatMomentsService.deleteByPrimaryKey(momentsId);
        return APIResultWrap.ok("删除成功！");
    }
}